package com.yocard.yxyd.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.SystemClock;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.ImageUtils;
import com.yocard.yxyd.utils.util.StringUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.yocard.yxyd.R;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.http.model.response.CsmOrderDetailBean;
import com.yocard.yxyd.http.model.response.OrderListBean;

import net.bither.util.NativeUtil;

import java.io.File;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created on 2019/4/10.
 */
public class CommonUtils {
    private static long mBackPressedTime;

    public static void doubleClickExitApp() {
        long curTime = SystemClock.uptimeMillis();
        if ((curTime - mBackPressedTime) < (3 * 1000)) {
            ActivityUtils.finishAllActivities();
            //根据进程ID，杀死该进程
            android.os.Process.killProcess(android.os.Process.myPid());
            //退出应用程序
            System.exit(0);
        } else {
            mBackPressedTime = curTime;
            ToastUtils.showLong("再按一次退出");
        }
    }

    /**
     * 检测是否安装支付宝
     * @param context
     * @return
     */
    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }

        return false;
    }

    public static void callPhone(Context mContext, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    public static String getStandardDate(String timeStr) {
        String temp = "";
        try {
            long now = System.currentTimeMillis() / 1000;
            long publish = Long.parseLong(timeStr);
            long diff = now - publish;
            long months = diff / (60 * 60 * 24 * 30);
            long days = diff / (60 * 60 * 24);
            long hours = (diff - days * (60 * 60 * 24)) / (60 * 60);
            long minutes = (diff - days * (60 * 60 * 24) - hours * (60 * 60)) / 60;
            if (months > 0) {
                temp = months + "月前";
            } else if (days > 0) {
                temp = days + "天前";
            } else if (hours > 0) {
                temp = hours + "小时前";
            } else {
                temp = minutes + "分钟前";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static String getFormalInt(Double decmal) {
        if(decmal == null){
            return "";
        }
        return new DecimalFormat("0").format(decmal);
    }

    public static String getFormal2Point(Double decmal) {
        if(decmal == null){
            return "";
        }
        return new DecimalFormat("0.00").format(decmal);
    }

    public static String getFormalForQiye(String decmal) {
        if (StringUtils.isEmpty(decmal)) {
            return "";
        }
        BigDecimal b1 = new BigDecimal(decmal);
        BigDecimal b2 = new BigDecimal("10000");
        if (b1.compareTo(b2) != -1) {
            Double s = BigDecimalUtil.divide(b1, b2).doubleValue();
            return getFormal2Point(s) + "万元";
        } else {
            return decmal + "元";
        }
    }

    public static String getPeriord(int periord) {
        String str = "";
        switch (periord) {
            case 0:
                str = "1-3";
                break;
            case 1:
                str = "3-6";
                break;
            case 2:
                str = "6-12";
                break;
            case 3:
                str = "12-18";
                break;
            case 4:
                str = "18-24";
                break;
            case 5:
                str = "24-36";
                break;
        }
        return str;
    }

    public static String getLoanTypeStr(String loanType) {
        String str = "";
        switch (loanType) {
            case Constants.LOAN_TYPE_XINYONG:
                str = "信用贷";
                break;
            case Constants.LOAN_TYPE_DIYA:
                str = "抵押贷";
                break;
            case Constants.LOAN_TYPE_CHEZHU:
                str = "车主贷";
                break;
            case Constants.LOAN_TYPE_ZHUANGXIU:
                str = "装修贷";
                break;
            case Constants.LOAN_TYPE_BANK:
                str = "银行贷";
                break;
        }
        return str;
    }

    public static String getCareerStr(String career) {
        String str = "";
        switch (career) {
            case Constants.CAREE_SHANGBAN:
                str = "上班族";
                break;
            case Constants.CAREE_ZIYOU:
                str = "自由职业";
                break;
            case Constants.CAREE_QIYE:
                str = "企业主";
                break;
            case Constants.CAREE_GETI:
                str = "个体户";
                break;
        }
        return str;
    }

    public static String getReceivedType(String type) {
        String str = "";
        switch (type) {
            case Constants.RECEIVED_CASH:
                str = "现金";
                break;
            case Constants.RECEIVED_CARD:
                str = "打卡";
                break;
        }
        return str;
    }

    public static String getMonth(String year) {
        String str = "";
        switch (year) {
            case Constants.MONTH_ONE_TO_THREE:
                str = "1-3月";
                break;
            case Constants.MONTH_THREE_TO_SIX:
                str = "3-6月";
                break;
            case Constants.MONTH_SIX_TO_TWELVE:
                str = "6-12月";
                break;
            case Constants.MONTH_TWELVE_TO_EIGHTEEN:
                str = "12-18月";
                break;
            case Constants.MONTH_EIGHTEEN_TO_TWENTY_FOUR:
                str = "18-24月";
                break;
            case Constants.MONTH_TWENTY_FOURT_TO_THIRTY_SIX:
                str = "24-36月";
                break;

        }
        return str;
    }

    public static String getYear(String year) {
        String str = "";
        switch (year) {
            case Constants.YEAR_BEFORE_ONE:
                str = "1年以下";
                break;
            case Constants.YEAR_ONE_AND_THREE:
                str = "1至3年";
                break;
            case Constants.YEAR_AFTER_THREE:
                str = "3年以上";
                break;
            case Constants.YEAR_ONE_AND_FIVE:
                str = "1-5年";
                break;
            case Constants.YEAR_AFTER_FIVE:
                str = "5年以上";
                break;

        }
        return str;
    }

    public static String getProfile(String profile) {
        String str = "";
        switch (profile) {
            case Constants.PROFILE_GOOD:
                str = "信用良好无逾期";
                break;
            case Constants.PROFILE_NONE:
                str = "无信用卡或贷款";
                break;
            case Constants.PROFILE_BEFORE3:
                str = "1年内逾期少于3次且少于90天";
                break;
            case Constants.PROFILE_AFTER3:
                str = "1年内逾期超过于3次或少于90天";
                break;
        }
        return str;
    }

    public static List<String> getZiliao(OrderListBean.OrderList item) {

        List<String> ziliao = new ArrayList<>();
        if (item.getIs_business_license() == 1) {
            ziliao.add("营业执照");
        }
        if (item.getIs_fund() == 1) {
            ziliao.add("公积金");
        }
        if (item.getIs_social_insurance() == 1) {
            ziliao.add("社保");
        }
        if (item.getIs_car() == 1) {
            ziliao.add("名下有车");
        }
        if (item.getIs_house() == 1) {
            ziliao.add("名下有房");
        }
        if (item.getIs_zhima() == 1) {
            ziliao.add("芝麻分");
        }
        if (item.getIs_weili() == 1) {
            ziliao.add("微粒贷");
        }
        if (item.getIs_bxbd() == 1) {
            ziliao.add("保单");
        }
        if(ziliao.size() == 0){
            ziliao.add("无");
        }

        return ziliao;
    }

    public static List<String> getZiliao(CsmOrderDetailBean.LoanEntity item) {

        List<String> ziliao = new ArrayList<>();
        if (item.getIs_business_license() == 1) {
            ziliao.add("营业执照");
        }
        if (item.getIs_fund() == 1) {
            ziliao.add("公积金");
        }
        if (item.getIs_social_insurance() == 1) {
            ziliao.add("社保");
        }
        if (item.getIs_car() == 1) {
            ziliao.add("名下有车");
        }
        if (item.getIs_house() == 1) {
            ziliao.add("名下有房");
        }
        if (item.getIs_zhima() == 1) {
            ziliao.add("芝麻分");
        }
        if (item.getIs_weili() == 1) {
            ziliao.add("微粒贷");
        }
        if (item.getIs_bxbd() == 1) {
            ziliao.add("保单");
        }

        if(ziliao.size() == 0){
            ziliao.add("无");
        }

        return ziliao;
    }

    public static int getImageRes(String ziliao) {
        int res = 0;
        switch (ziliao) {
            case "营业执照":
                res = R.mipmap.ico_zhizhao;
                break;
            case "公积金":
                res = R.mipmap.ico_gongjijin;
                break;
            case "社保":
                res = R.mipmap.ico_shebao;
                break;
            case "名下有车":
                res = R.mipmap.ico_car;
                break;
            case "名下有房":
                res = R.mipmap.ico_house;
                break;
            case "芝麻分":
                res = R.mipmap.ico_zhima;
                break;
            case "微粒贷":
                res = R.mipmap.ico_weili;
                break;
            case "保单":
                res = R.mipmap.ico_baodan;
                break;

        }
        return res;
    }

    public static String getStatus(String status) {
        String str = "";
        switch (status) {
            case Constants.CSM_STATUS_NOHANDLE:
                str = "未处理";
                break;
            case Constants.CSM_STATUS_NONEED:
                str = "客户不需要";
                break;
            case Constants.CSM_STATUS_ZIZHICHA:
                str = "资质太差";
                break;
            case Constants.CSM_STATUS_WURENJIETING:
                str = "无人接听";
                break;
            case Constants.CSM_STATUS_ZHONGDIANGJ:
                str = "重点跟进";
                break;
            case Constants.CSM_STATUS_LIANXIZHONG:
                str = "联系中";
                break;
            case Constants.CSM_STATUS_FANGKUAN:
                str = "已放款";
                break;
            case Constants.CSM_STATUS_QIANYUE:
                str = "已签约";
                break;
            case Constants.CSM_STATUS_STOP:
                str = "暂停跟进";
                break;
        }
        return str;
    }

    public static String getStatusType(String status) {
        String str = "";
        switch (status) {
            case "未处理":
                str = Constants.CSM_STATUS_NOHANDLE;
                break;
            case "客户不需要":
                str = Constants.CSM_STATUS_NONEED;
                break;
            case "资质太差":
                str = Constants.CSM_STATUS_ZIZHICHA;
                break;
            case "无人接听":
                str = Constants.CSM_STATUS_WURENJIETING;
                break;
            case "重点跟进":
                str = Constants.CSM_STATUS_ZHONGDIANGJ;
                break;
            case "联系中":
                str = Constants.CSM_STATUS_LIANXIZHONG;
                break;
            case "已放款":
                str = Constants.CSM_STATUS_FANGKUAN;
                break;
            case "已签约":
                str = Constants.CSM_STATUS_QIANYUE;
                break;
            case "暂停跟进":
                str = Constants.CSM_STATUS_STOP;
                break;
        }
        return str;
    }

    public static int getStatusColor(String status) {
        int resColorId = 0;
        switch (status) {
            case Constants.CSM_STATUS_LIANXIZHONG:
                resColorId = R.color.color6;
                break;
            case Constants.CSM_STATUS_NOHANDLE:
            case Constants.CSM_STATUS_WURENJIETING:
            case Constants.CSM_STATUS_ZHONGDIANGJ:
                resColorId = R.color.color_ff001f;
                break;

            case Constants.CSM_STATUS_NONEED:
            case Constants.CSM_STATUS_ZIZHICHA:
            case Constants.CSM_STATUS_FANGKUAN:
            case Constants.CSM_STATUS_QIANYUE:
            case Constants.CSM_STATUS_STOP:
                resColorId = R.color.color5;
                break;
            default:
                resColorId = R.color.color_ff001f;
                break;
        }
        return resColorId;
    }

    public static File saveImg(String filePath, String type) {
        Bitmap bitmap = ImageUtils.getBitmap(filePath);
        String destPath = AppContext.getContext().getExternalFilesDir("tempImg") + File.separator + type + ".png";
        File file = new File(destPath);
        if (file.exists()) {
            file.delete();
        }
        NativeUtil.compressBitmap(bitmap, file.getAbsolutePath());
        bitmap.recycle();
        return file;
    }

    public static File saveImg(int maxByte, String filePath, String type) {
        Bitmap bitmap = ImageUtils.getBitmap(filePath);
        String destPath = AppContext.getContext().getExternalFilesDir("tempImg") + File.separator + type + ".png";
        File file = new File(destPath);
        if (file.exists()) {
            file.delete();
        }
        NativeUtil.compressBitmap(bitmap, file.getAbsolutePath(), maxByte, NativeUtil.QUALITY_DEFAULT);
        bitmap.recycle();
        return file;
    }

    public static void openBroswer(Context mContext, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        mContext.startActivity(intent);
    }

    public static void installApk(File file, Context mContext) {
        //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mContext.startActivity(intent);
    }

    public static String getFormatMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return "";
        }
        String[] split = mobile.split("");
        List<String> tempList = new ArrayList<>(Arrays.asList(split));
        StringBuilder sb = new StringBuilder();
        int i;
        for (i = 0; i < tempList.size(); i++) {
            if (i >= 4 && i < 8) {
                sb.append("*");
            } else {
                sb.append(tempList.get(i));
            }
        }
        return sb.toString();
    }

    public static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }

        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (f.get(object) != null && !TextUtils.isEmpty(f.get(object).toString())) {
                    if (!f.get(object).toString().equals("0")) {
                        return false;
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
}
